package Groep1;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.io.BufferedReader;

public class Peer2Peer {

	private int sequenceNumber;

	public Peer2Peer() throws Exception {
		sequenceNumber = (int) (100 * Math.random());

		startReceiving();
		
		startSending();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			new Peer2Peer();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	public void startReceiving() {
		try {
			ServerSocket sSocket = new ServerSocket(863);
			
			Thread thread = new Thread(new ReceiverSocket(sSocket));

			thread.start();
			
			System.out.println("startReceiving!");
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void startSending() {
		sequenceNumber = 0;
		try {
			Socket socket = new Socket("localhost", 863);
			
			System.out.println("startSending!");
			System.out.println("Send message:");
			
			BufferedReader inFromOther;
			DataOutputStream outToOther;
			
			outToOther = new DataOutputStream(socket.getOutputStream());
			inFromOther = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			
			while (true) {
				Scanner in = new Scanner(System.in);


				try {
					if (!socket.isClosed())
						outToOther.writeBytes(sequenceNumber + " " +  in.nextLine() + "\n");
						sequenceNumber++;
						
						System.out.println("Received AcK: " + inFromOther.readLine());

				} catch (IOException e) {
					System.out.println("Write socket error: " + e);
				}
//				Scanner in = new Scanner(System.in);
				System.out.println("Send message:");
				//System.out.println(command);
				//return;
			}
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
